package com.surprise.webcommon.aspect;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.common.base.Stopwatch;
import com.surprise.webcommon.bo.CommonResponse;
import com.surprise.webcommon.logger.LogUtils;

/**
 * ElklogAspect.java
 * @author nick
 * 2015年4月1日
 */
@Aspect
@Component
public class ElklogAspect {
    @Around("@annotation(Elklog)")
    public Object operateAPILog(ProceedingJoinPoint joinPoint) throws Throwable {
        Stopwatch stopwatch = Stopwatch.createStarted();
        Object result = joinPoint.proceed();
        String usetime = stopwatch.stop().toString();
        
        Object[] req = joinPoint.getArgs();
        Object res = null;
        if (result != null && result instanceof CommonResponse) {
            res = ((CommonResponse) result).logItem();
        } else {
            res = result;
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Elklog elklog = method.getAnnotation(Elklog.class);

        HttpServletRequest httpRequest = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String ip = "";
        if (httpRequest != null) {
            ip = httpRequest.getRemoteHost();
        }

        LogItem logitem = new LogItem(elklog.value(), ip, usetime, req, res);
        LogUtils.log(logitem);
        return result;
    }
}
